package com.hsxshop.controller;

import com.hsxshop.model.ManagerUser;
import com.hsxshop.service.ManagerUserService;
import com.hsxshop.util.JsonTool;
import com.hsxshop.util.MD5Util;
import com.hsxshop.util.ParamConvertTool;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wangchongya on 17/6/26.
 */
@Controller
@RequestMapping(value = "/login/")
public class LoginController {

    @Resource(name = "managerUserService")
    private ManagerUserService managerUserService;

    @RequestMapping(value ="home", method = RequestMethod.GET)
    public String index(){

        return "login";
    }

    @RequestMapping(value ="do", method = RequestMethod.POST,produces= MediaType.APPLICATION_JSON_UTF8_VALUE,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String doAction(@RequestBody Map requestMap,HttpSession session){

        String username= ParamConvertTool.getParamStr(requestMap,"username");
        String password=ParamConvertTool.getParamStr(requestMap,"password");

        if("".equals(username.trim())){
            return JsonTool.returnObjectJsonErrorMsg("用户名不能为空");
        }

        if("".equals(password.trim())){
            return JsonTool.returnObjectJsonErrorMsg("密码不能为空");
        }

        String hql="from ManagerUser where username=?0";
        ManagerUser muser= managerUserService.getEntity(hql,username);

        if(null==muser){
            return JsonTool.returnObjectJsonErrorMsg("用户名或密码错误1");
        }else{
            if(muser.getPassword().equals(MD5Util.getMD5Str(password))){
                session.setAttribute("userToken",muser);
            }else{
                return JsonTool.returnObjectJsonErrorMsg("用户名或密码错误0");
            }
        }
        Map map=new HashMap();
        map.put("referer","/tpl/");
        return JsonTool.returnObjectJsonSuccess(map);
    }

}
